package com.atguigu.ggkt.vod.service.impl;

import com.atguigu.ggkt.vo.vod.ChapterVo;
import com.atguigu.ggkt.vo.vod.VideoVo;
import com.atguigu.ggkt.model.vod.Chapter;

import com.atguigu.ggkt.model.vod.Video;
import com.atguigu.ggkt.vod.mapper.ChapterMapper;
import com.atguigu.ggkt.vod.service.ChapterService;
import com.atguigu.ggkt.vod.service.VideoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author sleephardzz
 * @since 2023-07-10
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {

    @Autowired
    private VideoService videoService;
    //1查询大纲列表list[章节和小节]
    @Override
    public List<ChapterVo> getTreeList(Long courseId) {
        //根据课程courseId获取章节
        ArrayList<ChapterVo> voList = new ArrayList<>();
        QueryWrapper<Chapter> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        List<Chapter> chapterList = baseMapper.selectList(wrapper);
        //根据课程courseId获取小节
        LambdaQueryWrapper<Video> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Video::getCourseId, courseId);
        List<Video> videoList = videoService.list(wrapper1);

        //封装章节
        chapterList.stream().forEach(c->{
//            chapter->chapterVo
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(c, chapterVo);

            List<VideoVo> videoVoList = new ArrayList<>();
            //封装小节
            videoList.stream().forEach(v->{
//                video -> videoVo
                /**判断该v，是否是c下的内容
                 chapter-id = video-chapter_id*/
                if(c.getId() == v.getChapterId()){
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(v, videoVo);
                    videoVoList.add(videoVo);
                }
            });
            //最后把章节内所有小节，放到每个章节
            chapterVo.setChildren(videoVoList);
            voList.add(chapterVo);
        });
        return voList;
    }

    ////删除章节
    @Override
    public void removeChapterByCourseId(Long id) {
        LambdaQueryWrapper<Chapter> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Chapter::getCourseId, id);
        baseMapper.delete(wrapper);
    }
}
